<?php
namespace frontend\models\record;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\db\Connection;
use yii\db\Query;

class PostCategory extends Model
{
    /**
    post_category
    |- id name desc
     */
    public $id;
    public $name;
    public $desc;

    public static function tableName() {
        return 'post_category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['name', 'required'],
            [['id', 'desc'], 'safe'],
        ];
    }

    public function handleSubmit()
    {
        $error_array = array();
        $error_array['code'] = 1;
        $error_array['msg'] = 'invalid args';

        if (!$this->validate()) {
            $error_array['msg'] = 'validate failed';
            return $error_array;
        }

        if(Yii::$app->user->isGuest) {
            $error_array['msg'] = 'no user';
            return $error_array;
        }

        if(!Yii::$app->user->can('dev')) {
            $error_array['msg'] = 'user no permission';
            return $error_array;
        }

        if($this->id !== null
                && strlen($this->id) > 0) {
            try {
                Yii::$app->db->createCommand()
                    ->update($this->tableName(),[
                            'name' => $this->name,
                            'desc' => $this->desc,
                        ],
                        "id=:id",[
                            ":id" => $this->id,
                        ])
                    ->execute();
                $error_array['code'] = 0;
                $error_array['msg'] = 'update success';
            } catch (\Exception $e) {
                $error_array['msg'] = 'update failed';
            }
        } else {
            $query = new Query;
            $exists_in_post_group = $query->select(['id'])
                ->from($this->tableName())
                ->where(['name' => $this->name])
                ->createCommand(Yii::$app->db)
                ->queryScalar();
            if($exists_in_post_group === false) {
                try {
                    Yii::$app->db->createCommand()
                        ->insert($this->tableName(),[
                                'name' => $this->name,
                                'desc' => $this->desc,
                            ])
                        ->execute();
                    $error_array['code'] = 0;
                    $error_array['msg'] = 'insert success';
                } catch (\Exception $e) {
                    $error_array['msg'] = 'insert failed';
                }
            } else {
                $error_array['msg'] = 'name exists';
            }
        }

        return $error_array;
    }
}
